import React, { createContext, useContext, useState, useEffect } from 'react';
import { useColorScheme } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';

export type ThemeType = 'light' | 'dark' | 'system';

interface ThemeContextType {
  theme: ThemeType;
  currentTheme: 'light' | 'dark';
  setTheme: (theme: ThemeType) => void;
  colors: typeof lightColors;
}

const lightColors = {
  primary: '#007AFF',
  background: '#f5f5f5',
  card: '#ffffff',
  text: '#000000',
  border: '#cccccc',
  error: '#FF3B30',
  success: '#34C759',
  textSecondary: '#666666',
};

const darkColors = {
  primary: '#0A84FF',
  background: '#000000',
  card: '#1C1C1E',
  text: '#FFFFFF',
  border: '#38383A',
  error: '#FF453A',
  success: '#32D74B',
  textSecondary: '#EBEBF5',
};

const ThemeContext = createContext<ThemeContextType>({
  theme: 'system',
  currentTheme: 'light',
  setTheme: () => {},
  colors: lightColors,
});

export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const systemTheme = useColorScheme() || 'light';
  const [theme, setTheme] = useState<ThemeType>('system');
  const [currentTheme, setCurrentTheme] = useState<'light' | 'dark'>('light');

  useEffect(() => {
    loadTheme();
  }, []);

  useEffect(() => {
    const newTheme = theme === 'system' ? systemTheme : theme;
    setCurrentTheme(newTheme as 'light' | 'dark');
    saveTheme(theme);
  }, [theme, systemTheme]);

  const loadTheme = async () => {
    try {
      const savedTheme = await AsyncStorage.getItem('theme');
      if (savedTheme) {
        setTheme(savedTheme as ThemeType);
      }
    } catch (error) {
      console.error('加载主题失败:', error);
    }
  };

  const saveTheme = async (newTheme: ThemeType) => {
    try {
      await AsyncStorage.setItem('theme', newTheme);
    } catch (error) {
      console.error('保存主题失败:', error);
    }
  };

  const colors = currentTheme === 'light' ? lightColors : darkColors;

  return (
    <ThemeContext.Provider value={{ theme, currentTheme, setTheme, colors }}>
      {children}
    </ThemeContext.Provider>
  );
};

export const useTheme = () => useContext(ThemeContext); 